//
//  TLBaseTweetViewController.m
//  Coding_iOS
//
//  Created by taolei-mac on 2017/11/23.
//  Copyright © 2017年 com.lianchuan. All rights reserved.
//

#import "TLBaseTweetViewController.h"
#import "TLTweetDetailViewController.h"
#import "TLBannerView.h"
#import "TLTweetCell.h"
#import "TLHttpTool.h"
#import "TLBanner.h"
#import "TLTweet.h"
#import "TLTweetFrame.h"
#import "TLComment.h"

@interface TLBaseTweetViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) UITableView *tweetListView;

@property (nonatomic, weak) TLBannerView *bannerView;

@property (nonatomic, strong) NSMutableArray *tweetFrames;

@property (nonatomic, assign) BOOL hidden;
@property (nonatomic, assign) BOOL scrollUporDown;

@property (nonatomic, assign) BOOL drag;

@property (nonatomic, assign) BOOL refresh;

@property (nonatomic, assign) CGFloat offsetDistance;
@end

@implementation TLBaseTweetViewController

- (NSMutableArray *)tweetFrames
{
    if(!_tweetFrames){
        
        _tweetFrames = [NSMutableArray array];
    }
    return _tweetFrames;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addSubViews];
    
    [self getBanners];
    
    [self getPublicTweets];
}

/**
 *  添加子控件
 */
- (void)addSubViews
{
    // 添加一个UITableView
    UITableView *tweetListView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tweetListView.backgroundColor = [UIColor colorWithHexString:@"0xF2F4F6"];
    if(iOS11){
        tweetListView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    tweetListView.contentInset = UIEdgeInsetsMake(TLNavigationBarH + 44, 0, TLTabBarH, 0);
    tweetListView.delegate = self;
    tweetListView.dataSource = self;
    tweetListView.estimatedRowHeight = 0;
    tweetListView.estimatedSectionHeaderHeight = 0;
    tweetListView.estimatedSectionFooterHeight = 0;
    tweetListView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tweetListView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getPublicTweets)];
    tweetListView.mj_header.automaticallyChangeAlpha = YES;
    [tweetListView.mj_header beginRefreshing];
    [self.view addSubview:tweetListView];
    self.tweetListView = tweetListView;
    
    // 给tweetListView设置头部视图
    TLBannerView *bannerView = [[TLBannerView alloc] init];
    tweetListView.tableHeaderView = bannerView;
    bannerView.height = 195.0;
    self.bannerView = bannerView;
}

/**
 *  获取轮播图数据
 */
- (void)getBanners
{
    [TLHttpTool get:@"https://coding.net/api/banner/type/app" params:nil success:^(id responseObj) {
        
        NSArray *dicts = [responseObj objectForKey:@"data"];
        NSArray *banners = [TLBanner mj_objectArrayWithKeyValuesArray:dicts];
        self.bannerView.datas = [NSArray arrayWithArray:banners];
    } failure:^(NSError *error) {
        
        
    }];
}

/**
 *  将TLTweet模型数组转化成TLTweetFrame模型数组
 */
- (NSMutableArray *)tweetFramesWithTweets:(NSArray *)tweets
{
    NSMutableArray *frames = [NSMutableArray array];
    for (TLTweet *tweet in tweets) {
        TLTweetFrame *tweetFrame = [[TLTweetFrame alloc] init];
        tweetFrame.tweet = tweet;
        [frames addObject:tweetFrame];
    }
    return frames;
}

/**
 *  获取冒泡数据
 */
- (void)getPublicTweets
{
    self.refresh = YES;
    // 设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
    params[@"sort"] = @"time";
    
    @weakify(self)
    // 发送请求
    [TLHttpTool get:@"https://coding.net/api/tweet/public_tweets" params:params success:^(id responseObj) {
        
        @strongify(self)
        [self.tweetListView.mj_header endRefreshing];
        self.drag = NO;
        NSArray *tweets = [TLTweet mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"data"]];
        self.tweetFrames = [self tweetFramesWithTweets:tweets];
        [self.tweetListView reloadData];
    } failure:^(NSError *error) {
        @strongify(self)
        self.drag = NO;
        [self.tweetListView.mj_header endRefreshing];
    }];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tweetFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TLTweetCell *cell = [TLTweetCell createTweetCellWithTableView:tableView];
    cell.tweetFrame = self.tweetFrames[indexPath.row];
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TLTweetFrame *tweetFrame = self.tweetFrames[indexPath.row];
    return tweetFrame.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TLTweetDetailViewController *tweetDetailVc = [[TLTweetDetailViewController alloc] init];
    TLTweetFrame *tweetFrame = self.tweetFrames[indexPath.row];
    tweetDetailVc.tweet = tweetFrame.tweet;
    [self.navigationController pushViewController:tweetDetailVc animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.drag = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float newy = 0;
    static float oldy = 0;
    newy = scrollView.contentOffset.y;
    TLLog(@"%f", newy);
    self.offsetDistance = newy - oldy;
    if (newy != oldy ) {
        
        if (newy > oldy) { // 向上
            if(newy <= -(TLNavigationBarH + 44)){
                self.drag = NO;
            }
            self.scrollUporDown = YES;
        }else if(newy < oldy){ // 向下
           
            self.scrollUporDown = NO;
        }
        oldy = newy;
    }
    NSDictionary *dict = @{@"direction" : @(self.scrollUporDown), @"offsetDistance" : @(self.offsetDistance)};
    if(self.drag){

        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll" object:nil userInfo:dict];
    }
}

@end
